package com.jprocms.module.cms.controller.directive;

import com.jprocms.module.cms.dal.dataobject.content.ContentDO;
import com.jprocms.module.cms.service.content.ContentService;
import com.jprocms.module.cms.util.Freemarkers;
import com.jprocms.module.cms.web.Directives;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

import java.io.IOException;
import java.util.Map;

/**
 * 内容 自定义标签
 *
 * @author jprocms
 */
public class ContentDirective implements TemplateDirectiveModel {
    private static final String ID = "id";

    @SuppressWarnings("unchecked")
    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
            throws TemplateException, IOException {
        Freemarkers.requireLoopVars(loopVars);
        Freemarkers.requireBody(body);
        Long id = Directives.getLongRequired(params, ID);
        ContentDO contentDO = contentService.getContent(id);
        loopVars[0] = env.getObjectWrapper().wrap(contentDO);
        body.render(env.getOut());
    }

    private final ContentService contentService;

    public ContentDirective(ContentService contentService) {
        this.contentService = contentService;
    }
}
